package com.tabbar.demo.service;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;

import com.blankj.utilcode.util.ToastUtils;

/**
 * Created by dick on 2017/8/11.
 */

public class ForegroundEnablingService extends Service {
    private final String TAG = "bindService";
    private Notification.Builder builder;
    private static final int NOTIFICATION_ID = 10;
    private Notification notification;
    private NotificationReceiver notifactionReceiver;
    private NotificationReceiver receiver;
    private IntentFilter filter;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.w(TAG, "----->onCreate");
        registReceiver();
//        startAlarm();
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.w(TAG, "----->onStartCommand");
        startForeground();
        return START_STICKY;
    }


    private void startForeground() {
        if (notification == null) {
            notification = NotifacationManager.getInstance().getNotifaction(this);
        }
        startForeground(NOTIFICATION_ID, notification);// 开始前台服务
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        Log.w(TAG, "service关闭");
        ToastUtils.showShort("关闭service");
        unregisterReceiver(notifactionReceiver);
        stopForeground(true);
        super.onDestroy();
    }

    private void registReceiver() {
        if (receiver == null) {
            receiver = new NotificationReceiver();
        }
        if (filter == null) {
            filter = new IntentFilter();
            for (String action : NotificationReceiver.ACTIONS) {
                filter.addAction(action);
            }
        }
        registerReceiver(receiver, filter);
    }

    private void startAlarm() {
        Intent intent = new Intent(this, ForegroundEnablingService.class);
        PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0);
        AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        // 每分钟启动一次，这个时间值视具体情况而定
        alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 30 * 1000, pintent);
//        alarm.cancel(pintent);
    }
}